package com.ruoyi.common.utils.encryption;

import com.ruoyi.common.utils.Md5Encrypt;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Map;

public class YRKEncrypt {private static final String CHARSET_NAME ="UTF-8";
    private static final String CIPHER_NAME = "AES/CBC/PKCS5Padding";
    /**
     * 签名
     */
    public static String getSign(Map<String, String> paramMap, String signKey) {
        try {
            StringBuilder signBuilder = new StringBuilder();
            paramMap.forEach((k, v) -> {
                if(!k.equals("sign")){
                    signBuilder.append(v);
                }
            });
            //将传入的所有参数加秘钥后一起 MD5 计算的结果即为验证值
            return Md5Encrypt.md5(signBuilder.toString()+ signKey);
        }catch (Exception e){
            return null;
        }
    }
    /**
     * 加密
     */
    public static String encrypt(String content,String key,String iv) throws Exception {
        byte[] raw = key.getBytes(CHARSET_NAME);
        SecretKeySpec secretKey = new SecretKeySpec(raw, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes());
        Cipher cipher = Cipher.getInstance(CIPHER_NAME);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey,ivSpec);
        byte[] encrypted = cipher.doFinal(content.getBytes(CHARSET_NAME));
        return Base64.getEncoder().encodeToString(encrypted);
    }
    /**
     * 解密
     */
    public static String decrypt(String content,String key,String iv) throws Exception {
        byte[] raw = key.getBytes(CHARSET_NAME);
        SecretKeySpec secretKey = new SecretKeySpec(raw, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes());
        Cipher cipher = Cipher.getInstance(CIPHER_NAME);
        cipher.init(Cipher.DECRYPT_MODE, secretKey,ivSpec);
        return new String(cipher.doFinal(Base64.getDecoder().decode(content)));
    }
}
